<?php
namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class SiteconfigController extends Controller {

	public function __construct() {
		$this->middleware('role:siteconfig');
	}

	/**
	 * 修改 Meta 信息
	 */
	public function getMeta(Request $request) {
		$data['meta'] = config('site');
		$data['tongji'] = file_get_contents(public_path() . '/assets/tongji.js');
		return view('admin/siteconfig/meta', $data);
	}

	/**
	 * 编辑 Meta 信息
	 */
	public function postSetMeta(Request $request) {
		$name = strval($request->input('name'));
		$title = strval($request->input('title'));
		$keywords = strval($request->input('keywords'));
		$description = strip_tags($request->input('description'));
		$logo = config('site.logo');

		$tongji = $request->input('tongji');
		$js_file = realpath(public_path() . '/assets/tongji.js');
		if (file_exists($js_file)) {
			file_put_contents($js_file, $tongji);
		}

		$cfg_str = <<<EOF
<?php
return array(
  'name' => '$name',
  'title' => '$title',
  'keywords' => '$keywords',
  'description' => '$description',
  'logo' => '$logo',
);
EOF;

		$cfg_file = realpath(config_path() . DIRECTORY_SEPARATOR . 'site.php');
		if (!file_exists($cfg_file)) {
			return $this->error('配置文件丢失');
		}
		if (file_put_contents($cfg_file, $cfg_str)) {
			return $this->response('操作成功');
		}
		return $this->error('配置文件写入失败');
	}

	/**
	 * 进入 Logo 页面
	 */
	public function getLogo() {
		$logo = config('site.logo') ? config('site.logo') : 'upload/logo.png';
		return view('admin/siteconfig/logo')->withLogo(url($logo));
	}

	/**
	 * Logo 图片上传
	 */
	public function postUploadLogo(Request $request) {
		$file = $_FILES['Filedata'];

		$fileTypes = ['jpg', 'jpeg', 'gif', 'png']; // File extensions
		$file_ext = strtolower(pathinfo($file['name'])['extension']);
		if (!in_array($file_ext, $fileTypes)) {
			$result = ['status' => 0, 'msg' => '无效的图片格式'];
			return $this->response($result);
		}

		$target_path = 'upload/logo/';
		$targetPath = public_path() . DIRECTORY_SEPARATOR . $target_path;
		if (!is_dir($targetPath)) {
			if (!mkdir($targetPath, 0777, 1)) {
				$result = ['status' => 0, 'msg' => '无法建立上传目录'];
				return $this->response($result);
			}
		}
		$new_filename = uniqid(mt_rand()) . '.' . $file_ext;
		$result = move_uploaded_file($file['tmp_name'], $targetPath . $new_filename);
		if ($result === false) {
			$result = ['status' => 0, 'msg' => '保存文件失败'];
			return $this->response($result);
		}

		$new_file = $target_path . $new_filename;
		$cfg_file = realpath(config_path() . '/site.php');
		$cfg_str = file_get_contents($cfg_file);
		$pattern = '/([\s\S]*\'logo\' => \')(.*)(\'[\s\S]*)/s';
		$replacement = '$1' . $new_file . '$3';
		$new_str = preg_replace($pattern, $replacement, $cfg_str);
		file_put_contents($cfg_file, $new_str);

		$result = ['status' => 1, 'url' => asset($new_file)];
		return $this->response($result);
	}

}
